import { NextRequest, NextResponse } from 'next/server'
import { readPos, writePos, generateId } from '@/lib/data'
import { verifyToken } from '@/lib/auth'

export async function GET() {
	try {
		const items = readPos()
		return NextResponse.json({ success: true, items })
	} catch (e) {
		return NextResponse.json({ success: false, message: '获取词性失败' }, { status: 500 })
	}
}

export async function POST(request: NextRequest) {
	try {
		const token = request.cookies.get('token')?.value
		const decoded = verifyToken(token || '')
		if (!decoded || !decoded.isAdmin) {
			return NextResponse.json({ success: false, message: '需要管理员权限' }, { status: 403 })
		}
    const { key, name, englishName, description } = await request.json()
    if (!key || !name) {
			return NextResponse.json({ success: false, message: 'key 和 name 不能为空' }, { status: 400 })
		}
		const items = readPos()
		if (items.some(i => i.key === key)) {
			return NextResponse.json({ success: false, message: 'key 已存在' }, { status: 400 })
		}
    const item = { id: generateId(), key, name, englishName, description }
		items.push(item)
		writePos(items)
		return NextResponse.json({ success: true, item })
	} catch (e) {
		return NextResponse.json({ success: false, message: '创建词性失败' }, { status: 500 })
	}
}
